<template>
  <div id="CollegeLibrary">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="院校库" name="first">
        <schoolDate
          ref="schoolDateinfo"
          :storeType="1"
          :studentId="student_id * 1"
          :schoolData="schoolData"
        ></schoolDate>
        <div class="screen matop">
          <span class="screenSize">筛选条件:</span>
          <div class="flexwrap">
            <div
              v-for="(item, idx) in userSearchDate"
              class="screenTab between flexwrap"
              @click="delChange(idx, item)"
            >
              {{ item.name }}
              <el-icon size="12" style="margin-left: 2px; cursor: pointer">
                <Close />
              </el-icon>
            </div>
          </div>
          <div style="width: 100px"></div>
        </div>
        <library-list
          v-loading="collegeTableLoading"
          :collegeTableData="collegeTableData"
          @handleCollegeList="handleCollegeList"
          @handleCollegeDetails="handleCollegeDetails"
        />
        <div style="margin: 10px 0 20px 0">
          <el-pagination
            v-show="total"
            :current-page="requestData.page"
            :page-size="requestData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="专业库" name="second">
        <major-library
          v-if="activeName == 'second'"
          ref="majorLibraryRef"
          @changeTab="changeTab"
        />
      </el-tab-pane>
      <el-tab-pane label="职业库" name="third">
        <jorLibrary ref="jorLibraryRef" @goMajorlibrary="goMajorlibrary" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue';
import schoolDate from '@/views/leader/volunteer/module/schoolDate.vue'; // 学校
import majorLibrary from '../MajorLibrary';
import jorLibrary from '../jorLibrary';

import libraryList from '../ToolCollegeLibraryList';
import { searchSchool } from '../../api/appv2/appv1.js';

import { getLikeList } from '@/api/appv2/appv2';

import userSearch from '@/store/modules/searchInfoTool.js';
import bus from '@/utils/bus.js';
const jorLibraryRef = ref(null);
const student_id = localStorage.getItem('student_id');
const jobDataInfo = ref(null);
const schoolDateinfo = ref(null);
const majorLibraryRef = ref(null);
const userSearchVal = userSearch(); // 筛选仓库
let userSearchDate = computed(() => userSearchVal.searchArraylist); // 筛选数据
const collegeTableLoading = ref(false);
const collegeTableData = ref([]);
const activeName = ref('first');
const screenData = ref({}); // 筛选数据
const majorDataInfo = ref(null);
const volunteerSkipData = ref({});
const schoolData = ref([]);
const emit = defineEmits([
  'changeTab',
  'goMajorlibrary',
  'handleCollegeDetails',
]);

const changeTab = (data) => {
  if (jorLibraryRef.value) {
    jorLibraryRef.value.handleJorDetails(
      {
        code: data.code,
        name: data.name,
        children: [],
      },
      1
    );
  }
  emit('changeTab');
};
const goMajorlibrary = (data) => {
  emit('goMajorlibrary');
  let setInt = setInterval(() => {
    if (majorLibraryRef.value) {
      majorLibraryRef.value.handleOpenDet(data, data.level - 1);
      clearInterval(setInt);
    }
  }, 10);
};
// 请求数据
const requestData = ref({
  batch: '',
  page: 1,
  pageSize: 10,
  fronttype: 3,
  fType: 0, // 0-全部
  hasZJ: 0, // 0-全部
  order: '', // 排序 chance-录取率 rank-院校排名 planNum-招生计划
  is_sort: false, // 是否升序，false升序，true降序
});

const total = ref(0);
const handleClick = () => {
  jorLibraryRef.value.handleUpdateJorUi();
};
watch(
  // 监听院校筛选数据改变
  () => userSearchDate.value,
  () => {
    schoolSearchDataChange();
  }
);

// 删除全部筛选数据
bus.on('handleOpenJorDet', () => {
  activeName.value = 'third';
});
bus.on('handleOpenMajorDet', (data) => {
  activeName.value = 'second';
  volunteerSkipData.value = data;
  nextTick(() => {
    majorLibraryRef.value.handleOpenDet(data, data.level);
  });
});

const handleCollegeDetails = (mydata) => {
  emit('handleCollegeDetails', mydata);
};

const handleCollegeList = () => {
  requestData.value.page = 1;
  fetchSearchSchool();
};
const handleSizeChange = (val) => {
  requestData.value.pageSize = val;
  fetchSearchSchool();
};
const handleCurrentChange = (val) => {
  requestData.value.page = val;
  fetchSearchSchool();
};
const fetchLikeList = () => {
  let reqData = {
    detail: '1',
    type: 'school',
    studentId: localStorage.getItem('student_id'),
  };
  getLikeList(reqData)
    .then((res) => {
      schoolData.value = res.data.schoolDetail;
      let likeSchoolArr = res?.data?.school?.split(',') || [];
      likeSchoolArr.forEach((v) => {
        collegeTableData.value.forEach((item) => {
          if (item.code == v) {
            item.isSelected = true;
          }
        });
      });
    })
    .catch((err) => {
      console.log('err:', err);
    });
};
// 院校筛选数据改变
function schoolSearchDataChange() {
  let searchData = {
    province: [],
    categories: [],
    features: [],
    natureType: [],
    eduLevelSchool: [],
    schoolNewly: [],
    scode: [],
    mcode: [],
    zcode: [],
    ssearch: '',
    msearch: '',
    zsearch: '',
  };

  for (let item of userSearchDate.value) {
    switch (item.type) {
      case 'province':
        searchData.province.push(item.code);
        break;
      case 'type':
        searchData.categories.push(item.code);
        break;
      case 'school_feature':
        searchData.features.push(item.code);
        break;
      case 'nature':
        searchData.natureType.push(item.code);
        break;
      case 'school_type':
        searchData.eduLevelSchool.push(item.code);
        break;
      case 'schoolNewly':
        searchData.schoolNewly.push(item.code);
        break;
      case 'schoolSearch':
        searchData.scode.push(item.code);
        break;
      case 'major':
        searchData.mcode.push(item.code);
        break;
      case 'job':
        searchData.zcode.push(item.code);
        break;
      case 'ssearch':
        searchData.ssearch = item.name;
        break;
      case 'msearch':
        searchData.msearch = item.name;
        break;
      case 'zsearch':
        searchData.zsearch = item.name;
    }
  }

  let data = {
    province: searchData.province.toString(),
    categories: searchData.categories.toString(),
    features: searchData.features.toString(),
    natureType: searchData.natureType.toString(),
    eduLevelSchool: searchData.eduLevelSchool.toString(),
    schoolNewly: searchData.schoolNewly.toString(),
    scode: searchData.scode.toString(),
    mcode: searchData.mcode.toString(),
    zcode: searchData.zcode.toString(),
    ssearch: searchData.ssearch,
    msearch: searchData.msearch,
    zsearch: searchData.zsearch,
  };
  screenData.value = data;
  requestData.value.page = 1;
  fetchSearchSchool();
}

const fetchSearchSchool = (page) => {
  let data = {
    ...requestData.value,
    ...screenData.value,
  };

  data['zy_type'] = 3;

  Object.keys(data).forEach((key) => {
    if (data[key].length == 0) {
      delete data[key];
    }
  });

  collegeTableLoading.value = true;

  if (page && page.limit) {
    data.page = page.page;
    data.pageSize = page.limit;
  }
  searchSchool(data)
    .then((res) => {
      if (res.code == 20000) {
        total.value = Number(res.total);
        collegeTableData.value = res.data;
        collegeTableData.value.forEach((v) => {
          v.isSelected = false;
        });
        collegeTableLoading.value = false;
        if (localStorage.getItem('student_id')) {
          fetchLikeList();
        }
      } else {
        collegeTableLoading.value = false;
      }
    })
    .catch(() => {
      collegeTableLoading.value = false;
    });
};
fetchSearchSchool();
const handleCheckTabs = (tabType) => {
  activeName.value = tabType;
};
// 删除筛选条件信息
function delChange(idx, item) {
  if (item.type == 'major' || item.type == 'msearch') {
    // 专业
    majorDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'job' || item.type == 'zsearch') {
    // 职业
    jobDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'fType' || item.type == 'hasZJ') {
    // 高级
    if (item.type === 'fType') {
      fType.value = 0;
    } else {
      hasZJ.value = 0;
    }

    submitForm();
  } else {
    // 院校
    schoolDateinfo.value.deleteScreenItem(item);
  }
}

// 提交高级筛选
function submitForm() {
  if (
    requestData.value.fType != fType.value ||
    requestData.value.hasZJ != hasZJ.value
  ) {
    requestData.value.fType = fType.value;
    requestData.value.hasZJ = hasZJ.value;

    let arr = [];
    if (requestData.value.fType != 0) {
      arr.push({
        name: requestData.value.fType == 1 ? '仅看中外' : '不看中外',
        code: requestData.value.fType,
        type: 'fType',
      });
    }

    if (requestData.value.hasZJ != 0) {
      arr.push({
        name: requestData.value.hasZJ == 1 ? '仅看征集' : '不看征集',
        code: requestData.value.hasZJ,
        type: 'hasZJ',
      });
    }

    userSearchVal.saveAdvancedInfoChange(arr);
    showScreenPopover.value = false;
  }
}
defineExpose({
  handleCheckTabs,
});
</script>

<style lang="scss" scoped>
.screen {
  min-height: 50px;
  padding: 6px 0 6px 20px;
  background-color: #f9f9f9;
  display: flex;
  overflow: hidden;
  align-items: center;

  .screenSize {
    font-size: 12px;
    font-weight: 400;
    color: #3d3d3d;
    width: 55px;
  }

  .screenTab {
    padding: 7px 10px;
    margin: 2px 0;
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-left: 10px;
  }
}
</style>
